package com.mfp.java.testYou.ui.mvc;

import java.util.LinkedList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.mfp.java.testYou.core.AppContext;
import com.mfp.java.testYou.core.servlets.ManageTestServlet;
import com.mfp.java.testYou.core.utils.FormatUtils;
import com.mfp.java.testYou.db.model.Question;
import com.mfp.java.testYou.db.model.Test;
import com.mfp.java.testYou.model.UiSelectPair;

public class TestPage extends AbstractMVC {

            private static final Logger log = Logger.getLogger(TestPage.class);

	public static final String URL = "/testYou/pages/test.jsp";

	public static final String ATTR_EDIT_TEST = "editableTest";

	public static final Integer LIST_ELEMT_LENGHT = 70;
	public static final Integer LIST_SIZE = 10;

	private Test test;

	public TestPage(HttpServletRequest request, HttpServletResponse response) {
		super(request, response);
		init();
		prepareList();
	}

	private void init() {
		try {
			Object o = getRequest().getAttribute(ATTR_EDIT_TEST);
			if (o == null) {
				log.debug("No test found in request. Page is new Test Page");
				test = null;
				return;
			} else {
				log.debug("Test data found. Page is edit Test Page");
			}
			test = (Test) o;
		} catch (ClassCastException e) {
			log.error("Could not cast test class. Make sure to add test class as request attribute");
		}
	}

	private void prepareList() {
		if (!isEdit()) {
			return;
		}

		List<Question> list = AppContext.getDAO().getAllQuestions();
		List<UiSelectPair> uiList = new LinkedList<UiSelectPair>();
		for (Question q : list) {
			String text = FormatUtils.removeTags(q.getText(), LIST_ELEMT_LENGHT);
			uiList.add(new UiSelectPair(text, q.getId()));
		}

		getRequest().setAttribute(SelectListComponent.ATTR_LIST_DATA, uiList);
		getRequest().setAttribute(SelectListComponent.ATTR_LIST_NAME, ManageTestServlet.INPUT_QUESTIONID);
		getRequest().setAttribute(SelectListComponent.ATTR_LIST_SIZE, LIST_SIZE);
	}

	public boolean isEdit() {
		return test != null;
	}

	public String getTestTitle() {
		return test == null ? "" : test.getTitle();
	}

	public boolean isFinal() {
		return test == null ? false : test.isFinalTest();
	}

	public boolean isHintAllowed() {
		return test == null ? false : test.isAllowHints();
	}

	public Integer getTestId() {
		return test == null ? -1 : test.getId();
	}

	public List<UiSelectPair> getQuestions() {
		if (!this.isEdit()) {
			return null;
		}

		List<UiSelectPair> list = new LinkedList<UiSelectPair>();
		for (Question q : test.getQuestions()) {
			list.add(new UiSelectPair(FormatUtils.removeTags(q.getText(), LIST_ELEMT_LENGHT), q.getId()));
		}

		return list;
	}
}
